



//
//  NCommitFBViewController.m
//  nncloud
//
//  Created by macfai on 2018/9/21.
//  Copyright © 2018年 youedata. All rights reserved.
//

#import "NCommitFBViewController.h"
#import "SHAddHeader.h"
#import "UITextView+PlaceHolder.h"
#import "NMineCell.h"
#import "UITextView+PlaceHolder.h"
#import "STPickerSingle.h"
#import "NCommitBtnView.h"
#import "NUnitRoomModel.h"
#import <MJExtension/MJExtension.h>
@interface NCommitFBViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,STPickerSingleDelegate,SHAddImgViewDelegate,UITextFieldDelegate>

@property (nonatomic,strong)STPickerSingle *picker;

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSArray *titles;

@property (nonatomic, strong) SHAddImgView *addImgView;

//科室数据
@property (nonatomic,strong)NSMutableArray *unitArray;
//右侧标题
@property (nonatomic,strong)NSArray *tips;
@property (nonatomic,strong)NSArray *photos;
//相关的代表的数字
@property (nonatomic,assign)NSInteger problemTypeNumber;
@property (nonatomic,assign)NSInteger privacyNumber;
@property (nonatomic,assign)NSInteger unitNumber;

@property (nonatomic,strong)
NCommitBtnView *commitBtnView;

@property (nonatomic,copy)NSString *commitTitle;
@property (nonatomic,strong)UITextView *textView;
@property (nonatomic,strong)UITextField *titleTF;

////保存输入内容
@property (nonatomic,copy)NSString *inputContent;


@end



#define SectionHeaderHeight  15.f

@implementation NCommitFBViewController

#define cellIdentifier @"mineid"
-(UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight - 64) style:UITableViewStyleGrouped];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"NMineCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        
        _tableView.showsVerticalScrollIndicator = NO;
        
        //        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.privacyNumber = -1;
    self.unitNumber = -1;
    self.problemTypeNumber = -1;
    self.view.backgroundColor = kWhiteColor;
    [self.navigationItem setItemWithTitle:@"提交反馈" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.unitArray = [NSMutableArray array];
    self.titles = @[@"标题",@"",@"问题类型",@"所属单位",@""];
    [self.view addSubview:self.tableView];
    
    self.commitBtnView = [[[NSBundle mainBundle]loadNibNamed:@"NCommitBtnView" owner:self options:nil]lastObject];
    self.tableView.tableFooterView =  self.commitBtnView;
    [self.commitBtnView.commitBtn addTarget:self action:@selector(commitAction) forControlEvents:UIControlEventTouchUpInside];
    //暴力点击 限制
    self.commitBtnView.commitBtn.uxy_acceptEventInterval = 3.f;
    [self loadUnitData];
    
}

//- (void)noMoreData {
//    [self.tableView reloadData];
//    [self.tableView.mj_footer endRefreshingWithNoMoreData];
//}

- (void)formData:(NSArray *)data
{
    for (NSDictionary *dict in data) {
        NUnitRoomModel *model = [NUnitRoomModel mj_objectWithKeyValues:dict];
        NSString *name = model.officeName;
        [self.unitArray addObject:name];
    }
}
#pragma mark - 提交反馈
- (void)commitAction
{
    NSDictionary *dic;
    if (self.titleTF.text.length>0&&self.textView.text.length>0&&self.unit.length>0&&self.problemType.length>0) {
        
        dic = @{@"userId":[NUserModel shareInstance].userInfoId,
                              @"userName":[NUserModel shareInstance].userInfoName,
                              @"questionTitle":self.titleTF.text,
                              @"questionContent":self.textView.text,
                              @"questionType":@(self.problemTypeNumber),
                              @"questionPrivilege":@(2),//隐私设置统一改成自己可见2
                              @"officeName":self.unit};
        
    }else{
        
        [AFToast showText:@"请完善信息"];
        return;
        
    }
    [SVProgressHUD show];
    
    [NNetworkClient uploadImage:self.photos url:kCommitFeedbackUrl parameters:dic success:^(id responseObject) {
        
        YYLog(@"%@",responseObject);
        NSString *msg = responseObject[@"msg"];
        if ([responseObject[@"code"] isEqualToString:@"0"]) {
            
            [AFToast showText:@"提交成功"];
            
        }else{
            [AFToast showText:msg];
        }
        WeakStament(ws);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [ws.navigationController popViewControllerAnimated:YES];
        });
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];

}


///请求科室数据
- (void)loadUnitData {
    
    WeakStament(ws);
    ///更换成新的RC方式的请求方式
    [[NNRCNetRequest manager]getWithUrl:kKeshiRoomUrl params:nil success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"code"] isEqualToString:@"0"]) {
            NSArray *array = result[@"page"];
            [ws formData:array];
        }
    } failure:^(id failure) {
        YYLog(@"%@",failure);
    }];
    
}

#pragma mark - picker delegate
- (void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle{
    YYLog(@"%@",selectedTitle);
    
    if (pickerSingle.tag==111) {
        
        self.problemType = selectedTitle;
        
        if ([selectedTitle isEqualToString:@"咨询"]) {
            
            self.problemTypeNumber = 1;
            
        }else if ([selectedTitle isEqualToString:@"投诉"]){
            
            self.problemTypeNumber = 2;
            
        }else{
            
            self.problemTypeNumber = 3;
        }
        
        
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }else if (pickerSingle.tag==222){
        
//        self.privacy = selectedTitle;
//        if ([selectedTitle isEqualToString:@"公开该问题"]) {
//
//            self.privacyNumber = 1;
//
//        }else{
//
//            self.privacyNumber = 2;
//        }
//
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:3];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }else{
        self.unit = selectedTitle;
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:3];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

#pragma mark - delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    switch (indexPath.section) {
            
        case 2:
        {
            [self.textView resignFirstResponder];
            NSMutableArray *data = [NSMutableArray arrayWithArray:@[@"咨询",@"投诉",@"建议"]];
            STPickerSingle *single = [[STPickerSingle alloc]init];
            single.tag = 111;
            [single setArrayData:data];
            [single setTitle:@"问题类型"];
            [single setTitleUnit:@""];
            [single setDelegate:self];
            [single show];
            
        }
            break;
            
    
        case 3:
        {
            [self.textView resignFirstResponder];
            NSMutableArray *data = [self.unitArray copy];
            STPickerSingle *single = [[STPickerSingle alloc]init];
            single.tag = 333;
            [single setArrayData:data];
            [single setTitle:@"科室选择"];
            [single setTitleUnit:@""];
            [single setDelegate:self];
            [single show];
        }
            break;
            
        case 4:
        {
            //
        }
            break;
        default:
            break;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        
        return 100.f;
        
    }else if (indexPath.section==4){
        
        return 230.f;
        
    }else{
        return 55.f;
    }
    
}

#pragma mark - datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return  self.titles.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NMineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.nameLabelLeftMargin.constant = 25.f;
    cell.nameLabel.text = self.titles[indexPath.section];
    if (indexPath.section==0) {
        cell.arrowImg.hidden = YES;
        cell.titleTextField.hidden = false;
        
        self.commitTitle = cell.titleTextField.text;
        self.titleTF = cell.titleTextField;

        self.titleTF.delegate = self;
        
        if (self.ttitle.length>0) {
            self.titleTF.text = self.ttitle;
        }
    }
    if (indexPath.section==1) {
        
        [self setTextViewUIWithCell:cell];
    }
    if (indexPath.section==2) {
        cell.setLabel.hidden = false;
        //        cell.setLabel.text = @"咨询";
        
        if (self.problemType) {
            
             cell.setLabel.text = self.problemType;
            
        }
        
    }
    if (indexPath.section==3) {
        cell.setLabel.hidden = false;
        if (self.unit) {
            cell.setLabel.text = self.unit;
        }
        
        
    }
    if (indexPath.section==4) {
        [self setImageCellWithCell:cell];
    }
    return cell;
}

#pragma mark - textfield delegate  限制标题输入长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.titleTF) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.titleTF.text.length >= 100) {
            self.titleTF.text = [textField.text substringToIndex:100];
            return NO;
        }
    }
    return YES;
}

//图片cell
- (void)setImageCellWithCell:(NMineCell *)cell {
    
    cell.setLabel.hidden = YES;
    cell.arrowImg.hidden = YES;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(25, 10, 80, 18)];
    label.text = @"图片";
    label.textColor = kDarkGrayColor;
    label.font = kFont15;
    [cell.contentView addSubview:label];
    ///添加照片区域
    [self addPhotoAreaOnCell:cell];
    
}

///添加照片选择区域
- (void)addPhotoAreaOnCell:(NMineCell *)cell{
    SHAddImgView *addImgView = [[SHAddImgView alloc] initWithMaxColumn:4];
    addImgView.frame = CGRectMake(0, 30, ScreenWidth, 200);
    addImgView.configModel = [SHConfigModel creatNormalConfig];
    addImgView.backgroundColor = kWhiteColor;
    addImgView.delegate = self;
    addImgView.ImgBlock = ^(NSArray *photos) {
        YYLog(@"%@",photos);
        self.photos = photos;
    };
    _addImgView = addImgView;
    [cell.contentView addSubview:_addImgView];
}

///设置cell 内容
- (void)setTextViewUIWithCell:(NMineCell *)cell{
    cell.arrowImg.hidden = YES;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(25, 10, 80, 18)];
    label.text = @"内容描述";
    label.textColor = kDarkGrayColor;
    label.font = kFont14;
    [cell.contentView addSubview:label];
    
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, label.bottom+3, ScreenWidth-40, 60)];
    textView.delegate = self;
    textView.tag = 999;
    textView.font = kFont14;
    textView.delegate =self;
    textView.placeholder = @"请输入描述内容";
    textView.backgroundColor = kWhiteColor;
    self.textView = textView;
    
    [cell.contentView addSubview:textView];
}

#pragma mark - textView   delegate
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.tag==999) {
        
        self.inputContent = textView.text;
    }
}

#pragma mark - section head
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SectionHeaderHeight;//如果设置section的header高度，不设置footer高度，footer默认等于header高度
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, SectionHeaderHeight)];
    view.backgroundColor = kBackgroundColor;
    return view;
}

#pragma mark - section foot
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}


///解决table滑动 cell重用时 内容消失
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.textView.text.length<1) {
        self.textView.text =self.inputContent;
        self.textView.placeholder = @"";
    }
}

@end
